#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIDA Framework FastAPI 接口
提供PDF文档分析的REST API服务
"""

import os
import sys
import tempfile
import uuid
from pathlib import Path
from typing import Dict, Any
from datetime import datetime

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from loguru import logger

# 添加项目路径
sys.path.append(str(Path(__file__).parent))

# 导入AIDA核心模块
from main import AIDAPipeline

# 配置日志
logger.remove()
logger.add(
    sys.stdout,
    format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan> - <level>{message}</level>",
    level="INFO"
)

# 创建FastAPI应用
app = FastAPI(
    title="AIDA Framework API",
    description="智能文档分析框架 - 提供PDF文档的深度分析和审查服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 响应模型
class AnalysisResponse(BaseModel):
    success: bool
    message: str
    session_id: str = None
    analysis_result: Dict[str, Any] = None
    content: str = None  # 报告的完整文本内容
    processing_time: float = None
    error_details: str = None
    # 新增文件路径信息
    results_file: str = None  # JSON结果文件路径
    text_report_file: str = None  # Markdown报告文件路径
    results_directory: str = None  # 结果目录路径

class HealthResponse(BaseModel):
    status: str
    timestamp: str
    version: str

# 全局AIDA实例
aida_pipeline = None

@app.on_event("startup")
async def startup_event():
    """应用启动时初始化AIDA Pipeline"""
    global aida_pipeline
    try:
        # 从环境变量获取API密钥，或使用默认值
        api_key = os.getenv("OPENAI_API_KEY", "sk-umjpwhgrwtwcrifwfrczofcfeprfvhhcrvvpnbhkwrkvjnux")
        aida_pipeline = AIDAPipeline(api_key=api_key)
        
        # 初始化处理器
        if aida_pipeline._initialize_processors():
            logger.info("✅ AIDA Framework API 启动成功")
        else:
            logger.error("❌ AIDA Framework 初始化失败")
            raise Exception("AIDA Framework 初始化失败")
            
    except Exception as e:
        logger.error(f"启动失败: {str(e)}")
        raise e

@app.get("/", response_model=HealthResponse)
async def root():
    """根路径 - 健康检查"""
    return HealthResponse(
        status="healthy",
        timestamp=datetime.now().isoformat(),
        version="1.0.0"
    )

@app.get("/health", response_model=HealthResponse)
async def health_check():
    """健康检查接口"""
    return HealthResponse(
        status="healthy",
        timestamp=datetime.now().isoformat(),
        version="1.0.0"
    )

@app.post("/analyze", response_model=AnalysisResponse)
async def analyze_document(
    file: UploadFile = File(..., description="要分析的PDF文件")
):
    """
    分析PDF文档
    
    接收PDF文件并进行完整的AIDA分析流程：
    1. Stage1: 文档解析和内容提取
    2. Stage2: 向量化和索引构建  
    3. Stage3: 多代理审查和分析
    
    Args:
        file: 上传的PDF文件
        
    Returns:
        分析结果，包含文本形式的报告
    """
    if not aida_pipeline:
        raise HTTPException(status_code=500, detail="AIDA Framework 未初始化")
    
    # 验证文件类型
    if not file.filename.lower().endswith('.pdf'):
        raise HTTPException(status_code=400, detail="只支持PDF文件")
    
    # 生成唯一的会话ID
    session_id = str(uuid.uuid4())
    temp_file_path = None
    
    try:
        logger.info(f"🔄 开始处理文档: {file.filename} (会话ID: {session_id})")
        start_time = datetime.now()
        
        # 保存上传的文件到临时目录
        with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
            content = await file.read()
            temp_file.write(content)
            temp_file_path = temp_file.name
        
        logger.info(f"📁 临时文件保存至: {temp_file_path}")
        
        # 运行AIDA流水线
        pipeline_result = aida_pipeline.run_pipeline(temp_file_path)
        
        # 计算处理时间
        processing_time = (datetime.now() - start_time).total_seconds()
        
        # 检查pipeline_info中的success字段
        pipeline_info = pipeline_result.get("pipeline_info", {})
        if pipeline_info.get("success", False):
            # 提取文本报告
            analysis_text = ""
            stage3_results = pipeline_result.get("stage3_results")
            if stage3_results and stage3_results.get("success"):
                # 尝试从不同位置提取formatted_report
                if "formatted_report" in stage3_results:
                    analysis_text = stage3_results["formatted_report"]
                elif "analysis_results" in stage3_results:
                    analysis_results = stage3_results["analysis_results"]
                    if isinstance(analysis_results, dict):
                        # 尝试从summary_agent获取formatted_report
                        if "summary_agent" in analysis_results:
                            summary_result = analysis_results["summary_agent"]
                            if isinstance(summary_result, dict) and "formatted_report" in summary_result:
                                analysis_text = summary_result["formatted_report"]
                        # 如果没有找到，尝试从其他代理获取
                        if not analysis_text:
                            for agent_name, agent_result in analysis_results.items():
                                if isinstance(agent_result, dict) and "formatted_report" in agent_result:
                                    analysis_text = agent_result["formatted_report"]
                                    break
                
                if not analysis_text:
                    analysis_text = "分析完成，但未生成详细报告"
            else:
                analysis_text = "Stage3分析未完成"
            
            logger.info(f"✅ 文档分析完成 (耗时: {processing_time:.2f}秒)")
            
            return AnalysisResponse(
                success=True,
                message="文档分析完成",
                session_id=pipeline_info.get("session_id", session_id),
                analysis_result={
                    "report": analysis_text,
                    "pipeline_summary": {
                        "stage1_success": pipeline_result.get("stage1_results", {}).get("success", False),
                        "stage2_success": pipeline_result.get("stage2_results", {}).get("success", False),
                        "stage3_success": pipeline_result.get("stage3_results", {}).get("success", False),
                        "total_duration": processing_time
                    }
                },
                content=analysis_text,  # 添加报告文本内容到content字段
                processing_time=processing_time,
                # 添加文件路径信息
                results_file=pipeline_info.get("results_file"),
                text_report_file=pipeline_info.get("text_report_file"),
                results_directory=pipeline_info.get("results_directory")
            )
        else:
            # 处理失败
            error_details = "\n".join(pipeline_info.get("errors", ["未知错误"]))
            logger.error(f"❌ 文档分析失败: {error_details}")
            
            return AnalysisResponse(
                success=False,
                message="文档分析失败",
                session_id=session_id,
                processing_time=processing_time,
                error_details=error_details
            )
            
    except Exception as e:
        processing_time = (datetime.now() - start_time).total_seconds() if 'start_time' in locals() else 0
        error_msg = f"处理异常: {str(e)}"
        logger.error(error_msg)
        
        return AnalysisResponse(
            success=False,
            message="处理过程中发生异常",
            session_id=session_id,
            processing_time=processing_time,
            error_details=error_msg
        )
        
    finally:
        # 清理临时文件
        if temp_file_path and os.path.exists(temp_file_path):
            try:
                os.unlink(temp_file_path)
                logger.info(f"🗑️ 临时文件已清理: {temp_file_path}")
            except Exception as e:
                logger.warning(f"临时文件清理失败: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    
    # 运行FastAPI应用
    uvicorn.run(
        "api:app",
        host="0.0.0.0",
        port=8000,
        reload=True,)